<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="编辑业主"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="业主姓名" prop="ownerName">
            <el-input
              v-model="formData.ownerName"
              placeholder="请输入业主姓名"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!isEdit">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="formData.idCard"
              placeholder="请输入身份证号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="isEdit">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入联系电话"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" v-if="!isEdit">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入联系电话"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱地址" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" v-if="isEdit">
        <el-col :span="12">
          <el-form-item label="邮箱地址" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别" clearable style="width: 100%">
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
              <el-option label="未知" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="formData.birthDate"
              type="date"
              placeholder="请选择出生日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职业" prop="occupation">
            <el-input
              v-model="formData.occupation"
              placeholder="请输入职业"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作单位" prop="company">
            <el-input
              v-model="formData.company"
              placeholder="请输入工作单位"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入联系地址"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input
              v-model="formData.emergencyContact"
              placeholder="请输入紧急联系人"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急联系电话" prop="emergencyPhone">
            <el-input
              v-model="formData.emergencyPhone"
              placeholder="请输入紧急联系电话"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
                <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
      
      <el-form-item label="备注信息" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, nextTick } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ownerApi, type OwnerUpdateDTO, type OwnerEditData } from '@/api/owner'

// 定义props和emits
interface Props {
  visible: boolean
  ownerData?: OwnerEditData | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 计算属性
const isEdit = computed(() => !!props.ownerData)

// 表单数据 - 遵循Element Plus组件编码规范，使用undefined而不是null
const formData = reactive({
  ownerName: '',
  phone: '',
  email: '',
  gender: undefined as number | undefined,
  birthDate: '',
  address: '',
  occupation: '',
  company: '',
  emergencyContact: '',
  emergencyPhone: '',
  status: 1,
  remark: '',
  idCard: '' // 新增时需要身份证号
})

// 表单验证规则
const formRules: FormRules = {
  ownerName: [
    { required: true, message: '请输入业主姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '业主姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  idCard: [
    { 
      validator: (rule, value, callback) => {
        // 只在新增模式下进行身份证号校验
        if (!isEdit.value) {
          if (!value) {
            callback(new Error('请输入身份证号'))
            return
          }
          // 进行格式校验
          const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
          if (!pattern.test(value)) {
            callback(new Error('请输入正确的身份证号'))
            return
          }
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入联系电话'))
          return
        }
        // 进行格式校验
        const pattern = /^1[3-9]\d{9}$/
        if (!pattern.test(value)) {
          callback(new Error('请输入正确的手机号'))
          return
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  emergencyContact: [
    { required: true, message: '请输入紧急联系人', trigger: 'blur' }
  ],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入紧急联系电话'))
          return
        }
        // 进行格式校验
        const pattern = /^1[3-9]\d{9}$/
        if (!pattern.test(value)) {
          callback(new Error('请输入正确的手机号'))
          return
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    ownerName: '',
    phone: '',
    email: '',
    gender: undefined,
    birthDate: '',
    address: '',
    occupation: '',
    company: '',
    emergencyContact: '',
    emergencyPhone: '',
    status: 1,
    remark: '',
    idCard: ''
  })
  
  // 清除表单验证
  formRef.value?.clearValidate()
}

// 监听ownerData变化，初始化表单数据
watch(() => props.ownerData, (newData) => {
  if (newData) {
    // 编辑模式，填充表单数据
    Object.assign(formData, {
      ownerName: newData.ownerName || '',
      phone: newData.phone || '',
      email: newData.email || '',
      gender: newData.gender !== undefined ? newData.gender : undefined,
      birthDate: newData.birthDate || '',
      address: newData.address || '',
      occupation: newData.occupation || '',
      company: newData.company || '',
      emergencyContact: newData.emergencyContact || '',
      emergencyPhone: newData.emergencyPhone || '',
      status: newData.status !== undefined ? newData.status : 1,
      remark: newData.remark || '',
      idCard: newData.idCard || ''
    })
    
    // 延迟清除表单验证，确保数据完全加载后再清除
    nextTick(() => {
      setTimeout(() => {
        formRef.value?.clearValidate()
      }, 100)
    })
  } else {
    // 新增模式，重置表单数据
    resetForm()
  }
}, { immediate: true })

// 监听对话框显示状态，确保每次打开时清除验证错误
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    }
  }
)

// 取消操作
const handleCancel = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 调用真实的API接口
    if (isEdit.value) {
      // 编辑模式 - 使用OwnerUpdateDTO
      const submitData: OwnerUpdateDTO = {
        ownerName: formData.ownerName,
        phone: formData.phone, // 使用原始手机号数据
        email: formData.email,
        gender: formData.gender,
        birthDate: formData.birthDate,
        address: formData.address,
        occupation: formData.occupation,
        company: formData.company,
        emergencyContact: formData.emergencyContact,
        emergencyPhone: formData.emergencyPhone, // 使用原始紧急联系电话数据
        status: formData.status,
        remark: formData.remark
      }
      
      await ownerApi.updateOwner(props.ownerData!.id, submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式 - 使用OwnerDTO
      const submitData = { 
        ...formData,
        idCard: formData.idCard || '' // 新增时需要身份证号
      }
      
      const response = await ownerApi.createOwner(submitData)
      if (response.code === 200) {
        ElMessage.success('创建成功')
      } else {
        ElMessage.error(response.message || '创建失败')
        return
      }
    }
    
    emit('success')
    emit('update:visible', false)
    resetForm()
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
